const router = require('koa-router')();
const utils = require('../lib/utils');

/**
 * 获取menu by query
 */
router.get('/', httpResult.resp(async ctx => {
    let admin = ctx.session.admin;
    let query = ctx.request.query;

    return await models.suggestion.find(_.assign(query, {status : 1}));
}));

router.post('/', httpResult.resp(async  ctx => {
    let admin = ctx.session.admin;
    let menu = ctx.request.body;

    ctx.assert(menu, 'request body is empty');

    //valid create save
    isValidMenuItem(menu);
    if (menu._id) {
        await models.suggestion.updateOne({_id: menu._id}, {$set: menu});
    } else {
        menu = await models.suggestion.create(menu);
    }

    return menu;
}));
/**
 * 上传一组menu
 * query = {media_id : String}
 * body = Array
 */
router.post('/list', httpResult.resp(async ctx => {
    let admin = ctx.session.admin;
    let data = ctx.request.body;

    ctx.assert(data.media_id, 'request body is missing param : media_id');
    ctx.assert(data.list, 'request body is empty');
    ctx.assert(_.isArray(data.list), 'request body not array');
    ctx.assert(data.list.length < 12, 'max menu length = 11');
    data.list.forEach(item => item.media_id = data.media_id);
    let failList = [];
    //先将所有menu删除，body中正确出现的再恢复状态。
    await models.suggestion.update({media_id : data.media_id}, {$set : {status : 0}}, {multi : true});
    for(let item of data.list){
        try{
            //valid create save
            isValidMenuItem(item);
            if(item._id){
                await models.suggestion.updateOne({_id : item._id}, {$set : item});
            }else{
                let instance = await models.suggestion.create(item);
                item._id = instance._id;
            }
        }catch(err){
            failList.push(`${item.display_text} : ${err.message}`);
        }
    }
    if(failList.length > 0){
        throw JSON.stringify(failList);
    }else{
        return data.list.map(item => item._id);
    }
}));

const baseRules = [{
    key : 'display_text',
    required : true,
    message : 'no display text for terminal'
},{
    key : 'display_text',
    min : 0,
    max : 25,
    message : 'display text over length, length is 0 - 25'
},{
    key : 'type',
    enum : [0, 10, 20, 21, 30, 40, 50, 60, 70, 71],
    //0 = reply, 10 = url_action, 20 = map_action_query, 21 = map_action_latlng, 30=compose_TextMessage, 40=dialPhoneNumber,50=calendar, 60=device, 70=setting_disableAnonymization, 71=enableDisplayedNotifications
    message : 'type value is illegal'
},{
    key : 'post_back',
    max : 2048,
    message : 'post_back over length, length is 0 - 2048'
}];

const validRules = utils.validRules;
/**
 * 如果校验不通过抛出异常
 * @param item
 */
function isValidMenuItem(item){
    validRules(item, baseRules);
    switch (item.type) {
        case 10 : {
            validRules(item, [{
                key : 'url',
                required : true,
                message : 'param missing in type 10: url'
            },{
                key : 'url',
                regx : /^(?:(http|https|ftp):\/\/)?((?:[\w-]+\.)+[a-z0-9]+)((?:\/[^/?#]*)+)?(\?[^#]+)?(#.+)?$/i,
                message : 'url format is not valid'
            }]);
            break;
        }
        case 20 : {
            validRules(item, [{
                key : 'query',
                required : true,
                message : 'param missing in type 20: query'
            },{
                key : 'query',
                max : 200,
                min : 1,
                message : 'query length should in 1 ~ 200'
            }]);
            break;
        }
        case 21 : {
            validRules(item, [{
                key : 'latitude',
                required : true,
                message : 'param missing in type 21: latitude'
            },{
                key : 'longitude',
                required : true,
                message : 'param missing in type 21: longitude'
            },{
                key : 'label',
                max : 100,
                min : 1,
                message : 'label length should in 1 ~ 100'
            }]);
            break;
        }
        case 30 : {
            validRules(item, [{
                key : 'phone_number',
                required : true,
                message : 'param missing in type 30: phone_number'
            },{
                key : 'text',
                required : true,
                message : 'param missing in type 30: text'
            },{
                key : 'text',
                max : 100,
                min : 1,
                message : 'text length should in 1 ~ 100'
            }]);
            break;
        }
        case 40 : {
            validRules(item, [{
                key : 'phone_number',
                required : true,
                message : 'param missing in type 40: phone_number'
            }]);
            //没有break，41和40共用phone_number部分的rule
        }
        case 41 : {
            validRules(item, [{
                key : 'subject',
                max : 100,
                message : 'subject length should in 1 ~ 100'
            }]);
            break;
        }
        case 50 : {
            validRules(item, [{
                key : 'start_time',
                required : true,
                message : 'param missing in type 50: start_time'
            },{
                key : 'end_time',
                required : true,
                message : 'param missing in type 50: end_time'
            },{
                key : 'title',
                required : true,
                message : 'param missing in type 50: title'
            },{
                key : 'title',
                min : 1,
                max : 100,
                message : 'title length should in 1 ~ 100'
            },{
                key : 'start_time',
                regx : /^(\d{4})\-([0]{1}\d{1}|[1]{1}[0-2]{1})\-([0-2]{1}\d{1}|[3]{1}[0-1]{1})T([0-1]{1}\d{1}|[2]{1}[0-3]{1}):([0-5]{1}\d{1}):([0-5]{1}\d{1})Z$/,
                message : 'param start_time format should be like 2020-12-12T09:09:09Z'
            },{
                key : 'end_time',
                regx : /^(\d{4})\-([0]{1}\d{1}|[1]{1}[0-2]{1})\-([0-2]{1}\d{1}|[3]{1}[0-1]{1})T([0-1]{1}\d{1}|[2]{1}[0-3]{1}):([0-5]{1}\d{1}):([0-5]{1}\d{1})Z$/,
                message : 'param end_time format should be like 2020-12-12T09:09:09Z'
            },{
                key : 'description',
                min : 1,
                max : 500,
                message : 'description length should in 1 ~ 500'
            }]);
            break;
        }
    }
}

module.exports = router;
